<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <meta name="description" content="xms">
    <meta name="author" content="Xms">
    <link rel="icon" href="/content/favicon.ico">

    <title>安全角色 - 实体授权</title>

    <!-- Bootstrap core CSS -->
    <link href="/content/css/bootstrap3.3.5/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="/content/css/font-awesome.min.css" rel="stylesheet">
    <link href="/content/css/common.css" rel="stylesheet">
    <link href="/content/js/jquery-toast/jquery.toast.min.css" rel="stylesheet">
    <link id="themeLink" href="/content/css/theme/default.css" rel="stylesheet"/>
    <!-- Bootstrap core JavaScript ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="/content/js/jquery.min.js"></script>
    <script src="/content/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="/content/js/ie10-viewport-bug-workaround.js"></script>
    <script src="/content/js/jquery.bootstrap.min.js"></script>
    <script src="/content/js/json2.js"></script>
    <script src="/content/js/xms.utility.js"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.core.js"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.widget.js"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.mouse.js"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.draggable.js"></script>
    <script src="/content/js/jquery-toast/jquery.toast.min.js"></script>
    <script src="/content/js/xms.jquery.js"></script>
    <script src="/content/js/xms.web.js"></script>
    <script src="/content/js/commonlabels.js"></script>
    <script src="/content/js/common/pagecontext.js"></script>
    <script src="/api/user/usercontext"></script>
    <script>
        jQuery(function () {
            Xms.Web.Loading();
            if (typeof parent !== 'undefined') {
                if (parent != window) {//判断当前页面是否为子页面
                    $('body').addClass('xms-subpage');
                }
            }
        });

        function changeTheme(body, themename) {
            $("#themeLink").attr('href', '/content/css/theme/' + themename + '.css');
        }
    </script>
    <style>
        .dropdown-menu {
            min-width: 100px;
        }
    </style>
    <style>
        body {
            padding-top: 0;
        }
    </style>
</head>

<body data-spy="scroll" data-target="#myScrollspy">
<div class="container-fluid" id="body">
    <div class="row">
        <div class="shadeBox"
             style="background-color:#000000; opacity:0.5;width:100%;position:absolute;z-index:10;display:none;"></div>
        <div class="col-md-12" id="main" style="margin-bottom:80px;">
            <div><br class="breadcrumb"/></div>
            <div id="content"></div>
            <div class="page-render-wrap">
                <!--main-->
                <div class="container-fluid">
                    <div class="row" style="padding:5px 0px;">
                        <div class="col-sm-12 btn-group" id="owners">
                            <button type="button" class="btn btn-sm btn-default">类型：</button>
                        </div>
                    </div>
                </div>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            <a data-toggle="collapse"
                               href="#collapseTwo">
                                <strong id="rolename" class="text-primary"></strong> - <strong>实体权限</strong>
                            </a>
                        </h3>
                    </div>
                    <div id="collapseTwo" class="panel-collapse collapse in">
                        <div class="panel-body">
                            <form id="editform" class="form-horizontal" data-jsonajax="true" data-formdata="false"
                                  data-istip="true" action="/xms/api/security/roleobjectaccess/save" method="post">
                                <input data-val="true" id="RoleId" name="roleid" type="hidden"/>
                                <input id="ResourceName" name="ResourceName" type="hidden" />
                                <input id="TypeCode" name="typecode" type="hidden" value="4"/>
                                <ul id="myTab" class="nav nav-tabs" data-bind="foreach: entitygroups">
                                    <li>
                                        <a href="#tab_" data-toggle="tab"
                                           data-bind="text: label, attr:{href: '#tab_'+id}">
                                            CRM
                                        </a>
                                    </li>
                                </ul>
                                <div id="myTabContent" class="tab-content"
                                     data-bind="foreach: { data: entitygroups, as: 'group' }">
                                    <div id="tab_" data-bind="attr:{id: 'tab_'+id}" class="tab-pane fade"
                                         style="padding:5px;">
                                        <div class="form-group col-sm-12">
                                            <div class="table-responsive" style="overflow:initial;">
                                                <table class="table table-bordered table-condensed table-hover table-striped entities-container">
                                                    <thead>
                                                    <tr>
                                                        <th class="xms-checker" checkertype="all">实体</th>
                                                        <th class="xms-checker" checkertype="cum">读取</th>
                                                        <th class="xms-checker" checkertype="cum">创建</th>
                                                        <th class="xms-checker" checkertype="cum">修改</th>
                                                        <th class="xms-checker" checkertype="cum">删除</th>
                                                        <th class="xms-checker" checkertype="cum">共享</th>
                                                        <th class="xms-checker" checkertype="cum">分派</th>
                                                        <th class="xms-checker" checkertype="cum">追加</th>
                                                        <th class="xms-checker" checkertype="cum">追加到</th>
                                                        <!--<th class="xms-checker" checkertype="cum">导入</th>
                                                        <th class="xms-checker" checkertype="cum">导出</th>-->
                                                    </tr>
                                                    </thead>
                                                    <tbody data-bind="foreach: { data: group.children, as: 'entity' }">
                                                    <tr>
                                                        <td class="xms-checker" checkertype="col"
                                                            data-bind="attr:{'data-name': entity.name, 'data-mask': entity.mask}">
                                                            <label data-name="entityname"
                                                                   data-bind="text: entity.label"></label>
                                                        </td>
                                                        <!-- ko foreach: entity.children -->
                                                        <td data-bind="attr:{'data-mask': mask, 'title': label}">
                                                            <input type="hidden" name="objectid"
                                                                   data-name="entitypermissionid"
                                                                   data-bind="value: id"/>
                                                            <a href="javascript:void(0)" class="xms-checker-target">
                                                                <img class="mask-icon"
                                                                     src="/content/images/ico_18_role_x.gif"
                                                                     data-bind="attr:{'src': icon}"/>
                                                            </a>
                                                            <input type="hidden" name="mask" data-name="mask"
                                                                   data-bind="value: assignedmask"/>
                                                        </td>
                                                        <!-- /ko -->
                                                        <!--<td data-mask="2">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="3">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="4">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="5">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="10">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="6">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>
                                                        <td data-mask="7">
                                                          <input type="hidden" name="ObjectId" data-name="objectid" />
                                                          <a href="javascript:void(0)" class="xms-checker-target">
                                                            <img class="mask-icon" src="/content/images/ico_18_role_x.gif" />
                                                          </a>
                                                          <input type="hidden" name="mask" value="0" />
                                                        </td>-->
                                                    </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group col-sm-12">
                                    <table class="table">
                                        <caption><strong>标志说明</strong></caption>
                                        <tr>
                                            <td><img src="/content/images/ico_18_role_x.gif"/>无权限</td>
                                            <td><img src="/content/images/ico_18_role_b.gif"/>本人</td>
                                            <td><img src="/content/images/ico_18_role_l.gif"/>本部门</td>
                                            <td><img src="/content/images/ico_18_role_d.gif"/>本部门及下级部门</td>
                                            <td><img src="/content/images/ico_18_role_g.gif"/>全部</td>
                                        </tr>
                                    </table>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="pull-right hide" id="mask_dropdownmenu">
                    <div class="dropdown">
                        <button type="button" class="btn btn-link dropdown-toggle" id="mask_dropdownbtn"
                                data-toggle="dropdown">
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="mask_dropdownbtn">
                            <li role="presentation" class="dropdown-header">选择权限级别</li>
                            <li role="presentation">
                                <a role="menuitem" tabindex="-1" href="javascript:;" data-mask="0"><img
                                        src="/content/images/ico_18_role_x.gif"/>无权限</a>
                            </li>
                            <li role="presentation">
                                <a role="menuitem" tabindex="-1" href="javascript:;" data-mask="1"><img
                                        src="/content/images/ico_18_role_b.gif"/>本人</a>
                            </li>
                            <li role="presentation">
                                <a role="menuitem" tabindex="-1" href="javascript:;" data-mask="2"><img
                                        src="/content/images/ico_18_role_l.gif"/>本部门</a>
                            </li>
                            <li role="presentation">
                                <a role="menuitem" tabindex="-1" href="javascript:;" data-mask="4"><img
                                        src="/content/images/ico_18_role_d.gif"/>本部门及下级部门</a>
                            </li>
                            <li role="presentation">
                                <a role="menuitem" tabindex="-1" href="javascript:;" data-mask="16"><img
                                        src="/content/images/ico_18_role_g.gif"/>全部</a>
                            </li>
                        </ul>
                    </div>
                </div>

            </div>
            <nav class="navbar navbar-default navbar-fixed-bottom" role="navigation" id="body-footer">
                <div class="container">
                    <div class="navbar-form navbar-right" id="body-footer-content">
                        <div class="form-group col-sm-12 text-center" id="form-buttons">
                            <button type="button" id="save_button" class="btn btn-primary"><span
                                    class="glyphicon glyphicon-saved"></span> 保存
                            </button>
                        </div>
                    </div>
                </div>
            </nav>
        </div>
    </div>
</div>

<script src="/content/js/jquery.form.js"></script>
<script src="/content/js/jquery-validate/jquery.validate.min.js"></script>
<script src="/content/js/jquery-validate/localization/messages_zh.min.js"></script>
<script src="/content/js/xms.metadata.js"></script>
<script src="/content/js/knockout-2.2.0.js"></script>
<script>
    var FlagArray = new Array();
    FlagArray[0] = ['none', '/content/images/ico_18_role_x.gif', 0];
    FlagArray[1] = ['self', '/content/images/ico_18_role_b.gif', 1];
    FlagArray[2] = ['businessunit', '/content/images/ico_18_role_l.gif', 2];
    FlagArray[3] = ['businessunitandchild', '/content/images/ico_18_role_d.gif', 4];
    FlagArray[4] = ['organization', '/content/images/ico_18_role_g.gif', 16];
    var maskicons = [];
    maskicons['0'] = '/content/images/ico_18_role_x.gif';
    maskicons['1'] = '/content/images/ico_18_role_b.gif';
    maskicons['2'] = '/content/images/ico_18_role_l.gif';
    maskicons['4'] = '/content/images/ico_18_role_d.gif';
    maskicons['16'] = '/content/images/ico_18_role_g.gif';
    var model = $.urlParamObj(location.href);
    $(function () {
        $('#RoleId').val(model.roleid);
        $('#ResourceName').val(model.resourcename);

        $('#save_button').on('click', function(){$("#editform").submit();});
        $("#editform").submit(function () {
            var data = {};
            data.roleid = model.roleid;
            data.resourcename = model.resourcename;
            data.items = [];
            $('.entities-container').find('tbody>tr>td').each(function(i, n){
                var $objectid_input = $(n).find('input[name=objectid]');
                var $mask_input = $(n).find('input[name=mask]');
                if($mask_input.val() > 0){
                    data.items.push({objectid: $objectid_input.val(), mask: $mask_input.val()});
                }
            });
            console.log('post data', data);
            Xms.Web.Post('/api/security/roleobjectaccess/save', data, false, function(response){
                Xms.Web.Alert(response.IsSuccess, response.Content || response.ErrorMessage);
            }, null, true, false);
            return false;
        });
        getRoleInfo();
        loadResourceOwners();
        loadDatas();

        function setMaskState(obj) {
            var $obj = $(obj);
            var mask = $obj.next().val();
            var index = 0;
            $(FlagArray).each(function (i, n) {
                if (n[2] == mask || n[0] == 0) {
                    index = i + 1;
                    return;
                }
            });
            if (index == FlagArray.length) index = 0;
            mask = FlagArray[index][2];
            $obj.find('img').prop('src', FlagArray[index][1]);
            $obj.next().val(mask);
        }

        function setAllChecker(parentTable) {
            var checkers = parentTable.find(".xms-checker-target");
            checkers.each(function () {
                if ($(this).parents('tr:first').find('td:eq(0)').attr('data-mask') !== '4') {
                    setMaskState(this);
                } else {
                    scalingCul(this);
                }

            });
        }

        function setCumChecker(parentTable, index) {
            var checkers = parentTable.children("tbody").find("tr");
            checkers.each(function () {
                var item = $(this).find("td").eq(index);
                var ppp = item.find(".xms-checker-target");
                if (ppp.parents('tr:first').find('td:eq(0)').attr('data-mask') !== '4') {
                    setMaskState(item.children('a'));
                } else {
                    scalingCul(item.children('a'));
                }
            });
        }

        function setColChecker(parentTable, index) {
            var checkers = parentTable.children("tbody").find("tr").eq(index).find("td");
            var ppp = parentTable.children("tbody").find("tr");
            checkers.each(function () {
                var item = $(this).find("a.xms-checker-target");
                if (item.parents('tr').find('td:eq(0)').attr('data-mask') !== '4') {
                    setMaskState(item);
                } else {
                    scalingCul(item);
                }

            });
        }

        function scalingCul(obj) {
            var FlagArrays = new Array();
            FlagArrays[0] = ['none', '/content/images/ico_18_role_x.gif', 0];
            FlagArrays[1] = ['organization', '/content/images/ico_18_role_g.gif', 16];
            var $obj = $(obj);
            var flag = $obj.find('img').prop('src');
            var mask = $obj.next().val()
            if (mask) {
                var index = 0;
                $(FlagArrays).each(function (i, n) {
                    if (n[2] == mask || n[0] == 0) {
                        index = i + 1;
                        return;
                    }
                });
            } else {
                mask = $obj.attr('data-mask');
                var index = 0;
                $(FlagArrays).each(function (i, n) {
                    if (n[2] == mask || n[0] == 0) {
                        index = i;
                        return;
                    }
                });
            }
            if (index == FlagArrays.length) index = 0;
            mask = FlagArrays[index][2];
            $obj.find('img').prop('src', FlagArrays[index][1]);
            $obj.next().val(mask);
        }

        $('.entities-container').on('click', 'a', function (e) {
            if ($(this).parents('tr:first').find('td:eq(0)').attr('data-mask') !== 4) {
                //  setMaskState(this);
            } else {
                scalingCul(this);
            }
        });

        $(".xms-checker").on("click", function () {
            var index = $(this).parent("tr").find(this).index(),
                type = $(this).attr("checkertype"),
                parentTable = $(this).parents("table");

            if (type === "all") {
                setAllChecker(parentTable);
                //dianji(this);
            } else if (type === "cum") {
                setCumChecker(parentTable, index);
            } else if (type === "col") {
                // index = $(this).parent("tr").index();
                // setColChecker(parentTable, index);
            }
        });

        //$(".xms-checker").one("click", function () {
        //    var index = $(this).parent("tr").find(this).index(),
        //        type = $(this).attr("checkertype"),
        //        parentTable = $(this).parents("table");
        //    if (type === "all") {
        //        $('.xms-checker-target').find('img').prop('src', FlagArray[0][1]);
        //        $('.xms-checker-target').next().val(FlagArray[0][0]);
        //    }
        //});
        //$(".xms-checker").one("click", function () {
        //    var index = $(this).parent("tr").find(this).index(),
        //        type = $(this).attr("checkertype"),
        //        parentTable = $(this).parents("table");
        //    if (type === "cum") {
        //        var checkers = parentTable.children("tbody").find("tr");
        //        checkers.each(function () {
        //            var item = $(this).find("td").eq(index);
        //            item.find('.xms-checker-target>img').prop('src', FlagArray[0][1]);
        //            item.find('a').next().val(FlagArray[0][0]);
        //        })
        //    }
        //});

        $('.xms-checker-target').on('click', function (e) {
            e.stopPropagation();
            if ($(this).parents('tr').find('td:eq(0)').attr('data-mask') !== '4') {
                setMaskState(this)
            } else {
                scalingCul(this);
            }
        })
        //$(".xms-checker").one("click", function () {
        //    var index = $(this).parent("tr").find(this).index(),
        //        type = $(this).attr("checkertype"),
        //        parentTable = $(this).parents("table");
        //    if (type === "col") {
        //        index = $(this).parent("tr").index();
        //        var checkers = parentTable.children("tbody").find("tr").eq(index).find("td");
        //        checkers.each(function () {
        //            var item = $(this).find("a.xms-checker-target");
        //            if (item.length > 0) {
        //                item.find('img').prop('src', FlagArray[0][1]);
        //                item.next().val(FlagArray[0][0]);
        //            }
        //        })
        //    }
        //});
        appendMaskDropdownMenus();
        $('.xms-checker-target').addClass('btn btn-link');
    });

    function getRoleInfo(){
        Xms.Web.GetJson('/api/security/role/getbyid/' + model.roleid, null, function(data){
            if (!data.IsSuccess || !data.Content) {
                Xms.Web.FailureHandler(data);
                return;
            }
            data = data.Content;
            $('#rolename').text(data.name);
        });
    }

    function loadDatas() {
        Xms.Web.GetJson("/api/security/roleentitypermission?roleid=" + model.roleid, null, function (data) {
            if (!data.IsSuccess) {
                Xms.Web.FailureHandler(data);
                return;
            }
            data = data.Content;
            $(data).each(function (i, n) {
                if (!n.children) return true;
                $(n.children).each(function (ii, nn) {
                    if (!nn.children) return true;
                    $(nn.children).each(function (iii, nnn) {
                        nnn.icon = maskicons[nnn.assignedmask+''];
                    });
                });
            });
            console.log('data with icons', data);
            var Items = function () {
                var self = this;
                self.entitygroups = ko.observableArray(data);
            }
            ko.applyBindings(new Items());
            $('#myTab li:first').addClass('active');
            $('.tab-pane:first').addClass('in active');
            //补全td
            var cell_len = $('.entities-container:first').find('thead>tr>th').length;
            $('.entities-container').find('tbody>tr').each(function(i, n){
                var $tr = $(n);
                var _len = $tr.find('td').length;
                if(_len < cell_len){
                    console.log('补全td', cell_len, _len);
                    for (var j = 0;j < cell_len - _len;j++) {
                        $tr.append('<td></td>');
                    }
                }
            });
        }, null, false, 'GET', true);
    }

    function loadResourceOwners() {
        Xms.Web.GetJson(ORG_SERVERURL + "/api/security/resourceowners", null, function (data) {
            if (!data.IsSuccess) return;
            var items = data.Content;
            var resourceName = $('#ResourceName').val().toLowerCase();
            var $container = $('#owners');
            $(items).each(function (i, n) {
                if(!n.statecode) return true;
                var url = (n.uiendpoint || '/security/editrolepermission') + '?roleid=' + $("#RoleId").val() + '&resourcename=' + n.modulename;
                $container.append($('<button type="button" class="btn btn-sm ' + (resourceName == n.modulename.toLowerCase() ? 'btn-info' : 'btn-default') + '" data-url="' + url + '">' + (n.modulelocalizedname || n.modulename) + '</button>'));
            });
            $container.find('button').on('click', null, function () {
                Xms.Web.Redirect($(this).attr('data-url'));
            });
        });
    }

    function appendMaskDropdownMenus() {
        var m = $('#mask_dropdownmenu');
        $('.entities-container>tbody>tr').each(function (i, tr) {
            var type = $(tr).find('.xms-checker').attr('data-mask');
            var tdLen = 0;
            $(tr).find('td:gt(0)').each(function (k, td) {
                tdLen = k;
                var el = m.clone(true).removeClass('hide');
                el.prop('id', 'mask_dropdownmenu_' + k);
                if (type == 4) {
                    el.find('a').each(function (j, ela) {
                        var maskValue = $(ela).attr('data-mask');
                        if (maskValue != 0 && maskValue != 16) {
                            $(ela).parent('li').addClass('hide');
                        }
                    })
                }
                el.find('a').on('click', null, function (e) {
                    el.parents('td:first').find('input[name=mask]').val($(e.target).attr('data-mask'));
                    el.parents('td:first').find('input[name=mask]').siblings('.xms-checker-target').eq(0).find('img').prop('src', $(e.target).find('img').prop('src'));
                });
                $(td).find('input[name=mask]').after(el);
            });
            var headerEl = m.clone(true).removeClass('hide');
            headerEl.find('a').on('click', null, function (e) {
                var inputs = headerEl.parents('tr:first').find('input[name=mask]');
                inputs.val($(e.target).attr('data-mask'));
                inputs.each(function () {
                    $(this).siblings('.xms-checker-target').eq(0).find('img').prop('src', $(e.target).find('img').prop('src'));
                })
            });
            $(tr).each(function () {
                var $td = $(this).find('.xms-checker');
                var mask = $td.attr('data-mask');
                if (mask) {
                    if (mask == 4) {
                        headerEl.find('a').each(function (j, ela) {
                            var maskValue = $(ela).attr('data-mask');
                            if (maskValue != 0 && maskValue != 16) {
                                $(ela).parent('li').addClass('hide');
                            }
                        })
                    }
                }

                $(this).find('.xms-checker').append(headerEl);
            });
        });
    }
</script>

</body>
</html>